<!--
 * @Author: CoderLPF
 * @Date: 2020-03-30 09:23:13
 * @LastEditTime: 2020-05-05 18:28:23
 * @LastEditors: CoderLPF
 * @Description: 支付申请模块逻辑
 * @FilePath: \fzx-system-fd\src\views\modules\contract\application.vue
 -->

<template>
  <el-row :gutter="6">
    <myAnnounceDlg @operationSucc="operationState($event)" :configs="myAnnounceDlgConfig"></myAnnounceDlg>
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/contract' }">合同管理</el-breadcrumb-item>
          <el-breadcrumb-item>支付申请</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <!-- 主要操作区域 -->
      <el-col v-loading="config.loading" class="maincont-container">
        <div class="tab-container" v-if="config.tabShow">
          <el-tabs v-model="tabConfig.activeName">
            <el-tab-pane name="todo">
              <span slot="label">
                我的待办
                <el-badge
                  v-if="config.todoCount>0"
                  :value="config.todoCount"
                  style="margin-left:2px"
                ></el-badge>
              </span>
              <my-tableX
                v-if="tabConfig.activeName==='todo'"
                :configs="todoConfig.configs"
                :tableData="todoConfig.data"
                @dataAdd="addNewApply"
                @dataEdit="handleTodo"
              ></my-tableX>
            </el-tab-pane>
            <el-tab-pane label="运行记录" name="run">
              <my-tableX
                v-if="tabConfig.activeName==='run'"
                :configs="runingTaskConfig.configs"
                :tableData="runingTaskConfig.data"
                @dataView="viewDetail"
              ></my-tableX>
            </el-tab-pane>
            <el-tab-pane label="历史记录" name="finish">
              <my-tableX
                v-if="tabConfig.activeName==='finish'"
                :configs="completedTaskConfig.configs"
                :tableData="completedTaskConfig.data"
                @dataView="viewDetail"
              ></my-tableX>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="flow-container" v-if="!config.tabShow">
          <div class="flow-step fix">
            <my-stepX :configs="flowConfig.stepConfig"></my-stepX>
          </div>
          <div class="flow-form scrollable">
            <el-form
              ref="flowFormData"
              :validate-on-rule-change="false"
              :model="flowFormData"
              label-width="0px"
              size="small"
              :rules="formConfig.currentRule"
            >
              <h4 class="form-title">{{formConfig.formTitle}}</h4>
              <table border="1px" cellpadding="0" cellspacing="0" class="form-data">
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">合同名称</td>
                  <td colspan="4" width="40%">
                    <el-form-item label-width="0" :show-message="false" prop="contractName">
                      <el-input
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                        placeholder="合同名称"
                        v-model="flowFormData.contractName"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">合同编号</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="contractId">
                      <el-input
                        placeholder="合同编号"
                        v-model="flowFormData.contractId"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">请款单位</td>
                  <td colspan="4" width="40%">
                    <el-form-item label-width="0" :show-message="false" prop="company">
                      <el-input v-model="flowFormData.company" :readonly="true" size="small"></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">合同总额(万元)</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="contractAmount">
                      <el-input
                        v-model="flowFormData.contractAmount"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">已支付金额</td>
                  <td colspan="4" width="40%">
                    <el-form-item label-width="0" :show-message="false" prop="amountPaid">
                      <el-input
                        v-model="flowFormData.amountPaid"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">已支付次数</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="timePaid">
                      <el-input
                        v-model="flowFormData.timePaid"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">请款金额(大写)</td>
                  <td colspan="4" width="40%">
                    <el-form-item label-width="0" :show-message="false" prop="payAmountChi">
                      <el-input
                        v-model="flowFormData.payAmountChi"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">小写</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="payAmountNum">
                      <el-input
                        v-model="flowFormData.payAmountNum"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" rowspan="2" colspan="2" width="20%">请款依据</td>
                  <td colspan="8" width="80%">
                    <el-form-item label-width="0" :show-message="false" prop="payBasis">
                      <el-input
                        v-model="flowFormData.payBasis"
                        :readonly="flowState.step!==0||flowState.readonly"
                        type="textarea"
                        :rows="5"
                        placeholder="请输入请款依据"
                        resize="none"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">单位负责人</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="applicant">
                      <el-input
                        v-model="flowFormData.applicant"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">日期</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="createTime">
                      <el-input
                        v-model="flowFormData.createTime"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <!-- 勘察总体审核 -->
                <tr align="center">
                  <td class="form-label" rowspan="2" colspan="2" width="20%">勘察总体审核</td>
                  <td colspan="8" width="80%">
                    <el-form-item label-width="0" :show-message="false" prop="firstMessage">
                      <el-input
                        v-model="flowFormData.firstMessage"
                        :readonly="flowState.step!==1||flowState.readonly"
                        type="textarea"
                        :rows="5"
                        resize="none"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">审核人</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="firstApprover">
                      <el-input
                        v-model="flowFormData.firstApprover"
                        :readonly="flowState.step!==1||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">日期</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="firstTime">
                      <el-input
                        v-model="flowFormData.firstTime"
                        :readonly="flowState.step!==1||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <!-- 咨询单位审核 -->
                <tr align="center">
                  <td class="form-label" rowspan="2" colspan="2" width="20%">咨询单位审核</td>
                  <td colspan="8" width="80%">
                    <el-form-item label-width="0" :show-message="false" prop="secondMessage">
                      <el-input
                        v-model="flowFormData.secondMessage"
                        :readonly="flowState.step!==2||flowState.readonly"
                        type="textarea"
                        :rows="5"
                        resize="none"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">审核人</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="secondApprover">
                      <el-input
                        v-model="flowFormData.secondApprover"
                        :readonly="flowState.step!==2||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">日期</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="secondTime">
                      <el-input
                        v-model="flowFormData.secondTime"
                        :readonly="flowState.step!==2||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <!-- 业主单位审核-->
                <tr align="center">
                  <td class="form-label" rowspan="2" colspan="2" width="20%">建设单位审核</td>
                  <td colspan="8" width="80%">
                    <el-form-item label-width="0" :show-message="false" prop="thirdMessage">
                      <el-input
                        v-model="flowFormData.thirdMessage"
                        :readonly="flowState.step!==3||flowState.readonly"
                        type="textarea"
                        :rows="5"
                        resize="none"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">审核人</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="thirdApprover">
                      <el-input
                        v-model="flowFormData.thirdApprover"
                        :readonly="flowState.step!==3||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">日期</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="thirdTime">
                      <el-input
                        v-model="flowFormData.thirdTime"
                        :readonly="flowState.step!==3||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>

                <tr align="center">
                  <td class="form-label" rowspan="4" colspan="2" width="20%">备注</td>
                  <td class="form-label" colspan="2" width="20%">开户名</td>
                  <td colspan="6" width="60%">
                    <el-form-item label-width="0" :show-message="false" prop="bankCardName">
                      <el-input
                        v-model="flowFormData.bankCardName"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">开户银行</td>
                  <td colspan="6" width="60%">
                    <el-form-item label-width="0" :show-message="false" prop="bank">
                      <el-input
                        v-model="flowFormData.bank"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">银行账号</td>
                  <td colspan="6" width="60%">
                    <el-form-item label-width="0" :show-message="false" prop="bankCardId">
                      <el-input
                        v-model="flowFormData.bankCardId"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="2" width="20%">联系人</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="contact">
                      <el-input
                        v-model="flowFormData.contact"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">联系电话</td>
                  <td colspan="2" width="20%">
                    <el-form-item label-width="0" :show-message="false" prop="phone">
                      <el-input
                        v-model="flowFormData.phone"
                        :readonly="flowState.step!==0||flowState.readonly"
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </td>
                </tr>
              </table>
              <el-form-item class="btns">
                <el-button
                  v-if="!flowState.readonly"
                  @click="resolveflow"
                  type="primary"
                >{{flowConfig.btns.resolveText}}</el-button>
                <el-button
                  v-if="!flowState.readonly"
                  @click="rejectflow"
                  type="warning"
                >{{flowConfig.btns.rejectText}}</el-button>
                <el-button @click="cancelflow">{{flowConfig.btns.cancelText}}</el-button>
              </el-form-item>
            </el-form>
            <el-collapse>
              <el-collapse-item title="处理意见区" name="comment">
                <el-timeline style="text-align:left" :reverse="true">
                  <el-timeline-item
                    v-for="(activity, index) in flowComments"
                    :key="index"
                    :timestamp="activity.time"
                  >
                    <el-card>
                      <h3>审批意见</h3>
                      <h4>{{activity.message}}</h4>
                      <p>{{'单位：'+activity.group_name}}</p>
                      <p>{{'审核人：'+activity.approver}}</p>
                      <p>{{'联系方式：'+activity.cantact}}</p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </el-collapse-item>
            </el-collapse>
          </div>
          <myExportTableBtn :configs="exportTableConfig"></myExportTableBtn>
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import myTableX from "@/components/base/tableX";
import myStepX from "@/components/base/stepX";
import { formatDate } from "@/utils/date";
import myAnnounceDlg from "@/components/base/announceDlg";
import myExportTableBtn from "@/components/base/exportTableBtn";
// 全局变量
var glbVar = {};
var taskListParam = {};
var refRoles = []; //流程涉及到的角色列表
export default {
  components: {
    myTableX,
    myStepX,
    myAnnounceDlg,
    myExportTableBtn
  },

  data() {
    let glbcolumns = [
      { field: "tenders", name: "标段" },
      { field: "company", name: "请款单位" },
      { field: "contractId", name: "合同编号" },
      { field: "timePaid", name: "已支付次数" },
      { field: "applicant", name: "申请人" },
      { field: "createTime", name: "请款时间" }
    ];
    return {
      //导出按钮Config
      exportTableConfig: {
        isshown: false,
        subjectId: glbVar.subjectId,
        model: 11,
        flowFormData: this.flowFormData
      },
      // 系统全局配置
      config: {
        tabShow: true,
        todoCount: 0,
        loading: false
      },
      // tab页配置
      tabConfig: {
        activeName: "todo"
      },
      // 我的待办配置
      todoConfig: {
        configs: {
          nodata: "暂无待办事项",
          columns: glbcolumns,
          showFilterRow: {
            show: false
          },
          operationBtn: {
            show: true,
            add: true,
            addtext: "发起支付申请"
          },
          operationCol: {
            show: true,
            edit: true,
            options: {
              edit: {
                text: "处理"
              }
            }
          }
        },
        data: []
      },
      // 运行记录配置
      runingTaskConfig: {
        configs: {
          nodata: "暂无运行记录",
          columns: glbcolumns,
          showFilterRow: {
            show: true
          },
          operationBtn: {
            show: false
          },
          operationCol: {
            show: true,
            view: true,
            options: {
              view: {
                text: "详情"
              }
            }
          }
        },
        data: []
      },
      // 历史记录配置
      completedTaskConfig: {
        configs: {
          nodata: "暂无历史记录",
          columns: glbcolumns,
          showFilterRow: {
            show: true
          },
          operationBtn: {
            show: false
          },
          operationCol: {
            show: true,
            view: true,
            options: {
              view: {
                text: "详情"
              }
            }
          }
        },
        data: []
      },

      // 流程状态
      flowState: {
        step: 0,
        readonly: false,
        firstSend: true
      },

      // 表单配置
      formConfig: {
        formTitle: "北京城市副中心站勘察费用支付申请表",
        currentRule: {},
        rules: {
          node_1: {
            contractName: [{ required: true }],
            contractId: [{ required: true }],
            contractAmount: [{ required: true }],
            amountPaid: [{ required: true }],
            timePaid: [{ required: true }],
            payAmountChi: [{ required: true }],
            payAmountNum: [{ required: true }],
            payBasis: [{ required: true }],
            applicant: [{ required: true }]
          },
          node_2: {
            firstMessage: [{ required: true }],
            firstApprover: [{ required: true }]
          },
          node_3: {
            secondMessage: [{ required: true, trigger: "blur" }],
            secondApprover: [{ required: true, trigger: "blur" }]
          },
          node_4: {
            thirdMessage: [{ required: true, trigger: "blur" }],
            thirdApprover: [{ required: true, trigger: "blur" }]
          }
        }
      },

      // 流程配置
      flowConfig: {
        stepConfig: {
          active: 0,
          processstatus: "process",
          data: [
            { flow_node_name: "发起支付申请", description: "" },
            { flow_node_name: "勘察总体审核", description: "" },
            { flow_node_name: "咨询单位审核", description: "" },
            { flow_node_name: "建设单位审核", description: "" }
          ]
        },
        btns: {
          resolveText: "发送",
          rejectText: "重置",
          cancelText: "返回"
        }
      },

      //公告
      myAnnounceDlgConfig: {
        dialogFormVisible: false,
        isupdate: false,
        announceInfo: {
          remark: "",
          subject_id: "",
          url: "",
          notice_type: "支付情况",
          role: [],
          create_by: "",
          create_time: "",
          notice_content: "",
          notice_title: "支付情况完成",
          path: "",
          remark: ""
        }
      },

      // 数据字典数据
      dictData: {
        //工程列表
        roles: []
      },

      // 流程业务表单
      flowFormData: {
        id: 0,
        subjectId: "",
        tenders: "",
        major: "",
        contractName: "",
        contractId: "",
        company: "",
        contractAmount: "",
        amountPaid: "",
        timePaid: "",
        payAmountChi: "",
        payAmountNum: "",
        payBasis: "",
        bank: "",
        bankCardName: "",
        bankCardId: "",
        contact: "",
        phone: "",
        applicant: "",
        createTime: "", //创建时间

        firstMessage: "",
        firstApprover: "",
        secondMessage: "",
        secondApprover: "",
        thirdMessage: "",
        thirdApprover: "",
        firstTime: "",
        secondTime: "",
        thirdTime: ""
      },

      // 审批意见数据
      flowComments: [],

      // 业务数据
      businessData: {
        id: 0,
        subjectId: "",
        tenders: "",
        major: "",
        contractName: "",
        contractId: "",
        company: "",
        contractAmount: "",
        amountPaid: "",
        timePaid: "",
        payAmountChi: "",
        payAmountNum: "",
        payBasis: "",
        bank: "",
        bankCardName: "",
        bankCardId: "",
        contact: "",
        phone: "",
        applicant: "",
        createTime: "" //创建时间
      },

      // 发起流程的参数
      flowStartParam: {
        businessid: null,
        businesstype: "11",
        major: "",
        userid: null,
        path: ""
      },

      // 审批流程和重新发起的参数
      flowRunParam: {
        executionId: 0,
        flowNodeId: 0,
        message: "",
        procInstId: 0,
        userId: 0,
        time: "",
        contact: "",
        parent: 0,
        approver: ""
      }
    };
  },

  // 初始化
  created() {
    glbVar.subjectId = this.$store.state.projectInfo.projectName;
    glbVar.user = this.$store.state.m_user.userInfo;
    this.flowFormData.subjectId = glbVar.subjectId;
    this.flowStartParam.userid = glbVar.user.id;
    this.flowStartParam.path = this.$route.path;

    taskListParam = {
      projectId: glbVar.subjectId,
      businessType: 11, //业务类型代码
      userId: glbVar.user.id
    };

    if (glbVar.user.user_type === "1") {
      this.todoConfig.configs.operationBtn.show = true;
    } else {
      this.todoConfig.configs.operationBtn.show = false;
    }

    // let query = this.$route.query;
    // if (query.id && query.todo) {
    //   this.config.tabShow = false;
    //   this.$api.payapply
    //     .getbyid(query.id)
    //     .then(res => {
    //       if (res.code === 200) {
    //         this.handleTodo(res.data);
    //       } else {
    //         console.log("get todo business detail:" + res.msg);
    //         this.$message.error("get todo business detail:" + resizeBy);
    //       }
    //     })
    //     .catch(err => {
    //       console.log("get todo business detail:" + err);
    //       this.$message.error("get todo business detail:" + err);
    //     });
    // }

    let query = this.$route.query;
    if (Object.keys(query).length != 0) {
      this.config.tabShow = false;
      if (query.todo) {
        this.$api.payapply
          .getbyid(query.id)
          .then(res => {
            if (res.code === 200) {
              this.handleTodo(res.data);
            } else {
              console.log("get todo business detail:" + res.msg);
            }
          })
          .catch(err => {
            console.log("get todo business detail:" + err);
            this.$message.info("get todo business detail:" + err);
          });
      } else if (query.id && !query.todo) {
        this.$api.payapply
          .getbyid(query.remark)
          .then(res => {
            if (res.code === 200) {
              this.viewDetail(res.data);
            } else {
              console.log("get todo business detail:" + res.msg);
            }
          })
          .catch(err => {
            console.log("get todo business detail:" + err);
            this.$message.info("get todo business detail:" + err);
          });
      }
    }
  },

  mounted() {
    this.initList();

    //文件导出 是否可见
    this.exportTableConfig.isshown =
      this.flowState.readonly && this.flowState.step == 4;
    this.exportTableConfig.subjectId = glbVar.subjectId;
  },

  watch: {
    $route(to, from) {
      if (to.path === from.path && to.query !== from.query) {
        this.initList();
      }
    },
    //文件导出 是否可见 监听变化
    "flowConfig.formState.readonly"(newstate, old) {
      this.exportTableConfig.isshown =
        this.flowState.readonly && this.flowState.step == 4;
    },
    "flowState.step"(newstate, old) {
      if (newstate == 4) {
        this.exportTableConfig.isshown =
          this.flowState.readonly && this.flowState.step == 4;
      }
    },
    flowFormData(newstate, old) {
      this.exportTableConfig.flowFormData = newstate;
    }
  },

  methods: {
    // exportTable() {
    //   //数据准备
    //   console.log("look at me");
    //   console.log(this.flowFormData);

    //   this.$confirm("是否导出制式表格?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       this.$api.exportTable
    //         .getUrl(
    //           {
    //             subjectId: glbVar.subjectId,
    //             model: 11
    //           },
    //           this.flowFormData
    //         )
    //         .then(res => {
    //           if (res.code == 200) {
    //             this.$message.success("导出成功!");
    //             window.open(res.data.url);
    //             // this.listShow = !this.listShow;
    //             // this.initList();
    //           }
    //         })
    //         .catch(err => {
    //           this.$message.error("导出失败!!" + err);
    //         });
    //     })
    //     .catch(() => {
    //       return;
    //     });
    // },

    // 初始化各个列表
    initList() {
      // 初始化列表
      this.$api.startitem
        .getmytasklist(taskListParam)
        .then(res => {
          if (res.code === 200) {
            if (!res.data || res.data.length === 0) {
              this.todoConfig.data = [];
              // this.$message.info("暂无待办事项");
              return;
            }
            this.$api.payapply
              .getbyids(res.data)
              .then(res => {
                if (res.code === 200) {
                  this.todoConfig.data = res.data;
                } else {
                  console.log("get todo business detail:" + res.msg);
                  this.$message.info("get todo business detail:" + res);
                }
              })
              .catch(err => {
                console.log("get todo business detail:" + err);
                this.$message.info("get todo business detail:" + err);
              });
          } else {
            console.log("get todo ids res:" + res.msg);
          }
        })
        .catch(err => {
          console.log("get todo ids res:" + err);
        });

      this.$api.startitem
        .getprocessinglist(taskListParam)
        .then(res => {
          if (res.code === 200) {
            console.log("lenght:" + res.data.length);

            if (!res.data || res.data.length === 0) {
              this.runingTaskConfig.data = [];
              // this.$message.info("暂无运行流程");
              return;
            }
            this.$api.payapply
              .getbyids(res.data)
              .then(res => {
                if (res.code === 200) {
                  this.runingTaskConfig.data = res.data;
                } else {
                  console.log("get runing business detail:" + res.msg);
                }
              })
              .catch(err => {
                console.log("get runing business detail:" + err);
                this.$message.info("get runing business detail:" + err);
              });
          }
        })
        .catch(err => {
          console.log("get runing ids res:" + err);
        });
      this.$api.startitem
        .getfinishedlist(taskListParam)
        .then(res => {
          if (res.code === 200) {
            if (!res.data || res.data.length === 0) {
              this.completedTaskConfig.data = [];
              // this.$message.info("暂无历史流程");
              return;
            }
            this.$api.payapply
              .getbyids(res.data)
              .then(res => {
                if (res.code === 200) {
                  this.completedTaskConfig.data = res.data;
                } else {
                  console.log("get finished business detail:" + res.msg);
                }
              })
              .catch(err => {
                console.log("get finished business detail:" + err);
                this.$message.info("get finished business detail:" + err);
              });
          }
        })
        .catch(err => {
          console.log("get finished business detail:" + err);
        });
    },

    //监听上传公告结果
    operationState(msg) {
      console.log(msg);
      if (msg) {
        this.$message.success("公告发布成功");
        this.refresh();
      } else {
        this.$message.error("发布失败");
        this.refresh();
      }
    },

    // 刷新列表
    refresh() {
      if (this.$route.query.id) {
        this.$router.replace({ path: this.$route.path, query: {} });
        this.initList();
        this.config.tabShow = true;
      } else {
        this.initList();
        this.config.tabShow = true;
      }
    },

    /**
     * @description: 发起一个变更申请,预操作
     */
    addNewApply() {
      this.initFlowFormData_Add();
      this.flowFormData.tenders = glbVar.user.nick_name; //标段
      this.flowFormData.subjectId = glbVar.subjectId; // 项目名称
      this.flowFormData.company = glbVar.user.company; //请款单位
      this.flowState.readonly = false;
      this.changeStep(0); // 切换当前步骤
      this.config.tabShow = false;
      this.flowState.firstSend = true;
    },

    initFlowFormData_Add() {
      this.flowFormData = {
        id: 0,
        subjectId: "",
        tenders: "",
        major: "",
        contractName: "",
        contractId: "",
        company: "",
        contractAmount: "",
        amountPaid: "",
        timePaid: "",
        payAmountChi: "",
        payAmountNum: "",
        payBasis: "",
        bank: "",
        bankCardName: "",
        bankCardId: "",
        contact: "",
        phone: "",
        createTime: "", //创建时间
        applicant: "",

        firstMessage: "",
        firstApprover: "",
        secondMessage: "",
        secondApprover: "",
        thirdMessage: "",
        thirdApprover: "",
        firstTime: "",
        secondTime: "",
        thirdTime: ""
      };

      this.flowStartParam.userid = glbVar.user.id;
      this.flowStartParam.path = this.$route.path;
    },

    initFlowFormData_Handle(row) {
      this.initFlowFormData_Add();
      this.flowFormData.id = row.id;
      this.flowFormData.subjectId = row.subjectId;
      this.flowFormData.tenders = row.tenders;
      this.flowFormData.major = row.major;
      this.flowFormData.contractName = row.contractName;
      this.flowFormData.contractId = row.contractId;
      this.flowFormData.company = row.company;
      this.flowFormData.contractAmount = row.contractAmount;
      this.flowFormData.amountPaid = row.amountPaid;
      this.flowFormData.timePaid = row.timePaid;
      this.flowFormData.payAmountChi = row.payAmountChi;
      this.flowFormData.payAmountNum = row.payAmountNum;
      this.flowFormData.payBasis = row.payBasis;
      this.flowFormData.bank = row.bank;
      this.flowFormData.bankCardName = row.bankCardName;
      this.flowFormData.bankCardId = row.bankCardId;
      this.flowFormData.contact = row.contact;
      this.flowFormData.phone = row.phone;
      this.flowFormData.applicant = row.applicant;
      this.flowFormData.createTime = row.createTime;
    },

    /**
     * @description: 处理待办任务
     */
    handleTodo(row) {
      console.log(row);

      let r_id = row.id;
      this.initFlowFormData_Handle(row);

      // 初始化公告默认角色列表
      this.$api.startitem.getRoleByRuningInfo(11, r_id).then(res => {
        if (res.code === 200) {
          refRoles = res.data;
        }
      });

      this.$api.startitem
        .isfirsttime({
          businesstype: 11,
          businessid: r_id
        })
        .then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.flowState.firstSend = true;
            } else {
              this.flowState.firstSend = false;
            }

            this.$api.startitem
              .getworkflow({
                businessType: 11,
                businessId: r_id
              })
              .then(res => {
                if (res.code === 200) {
                  console.log(res.data);

                  let { id, proc_inst_id } = res.data;
                  this.$api.startitem
                    .getcurrentstage({
                      executionId: id,
                      procInstId: proc_inst_id
                    })
                    .then(res => {
                      if (res.code === 200) {
                        this.flowState.readonly = false;
                        this.config.tabShow = false;

                        console.log("step id");

                        console.log(res.data);

                        this.changeStep(res.data[0]);
                        this.initComments(r_id);

                        this.flowRunParam.executionId = id;
                        this.flowRunParam.flowNodeId = res.data[1];
                        this.flowRunParam.message = "";
                        this.flowRunParam.procInstId = proc_inst_id;
                        this.flowRunParam.userId = glbVar.user.id;
                      }
                    });
                }
              });
          }
        });
    },

    // 查看流程运行详情,运行时
    viewDetail(row) {
      let r_id = row.id;
      this.initFlowFormData_Handle(row);

      this.$api.startitem
        .isfirsttime({
          businesstype: 11,
          businessid: r_id
        })
        .then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.flowState.firstSend = true;
            } else {
              this.flowState.firstSend = false;
            }

            this.$api.startitem
              .getworkflow({
                businessType: 11,
                businessId: r_id
              })
              .then(res => {
                if (res.code === 200) {
                  console.log(res.data);

                  let { id, proc_inst_id } = res.data;
                  this.$api.startitem
                    .getcurrentstage({
                      executionId: id,
                      procInstId: proc_inst_id
                    })
                    .then(res => {
                      if (res.code === 200) {
                        this.flowState.readonly = true;
                        this.config.tabShow = false;

                        this.changeStep(res.data[0]);
                        this.initComments(r_id);
                      }
                    });
                }
              });
          }
        });
    },

    // 执行流程
    resolveflow() {
      // 预验证
      this.$refs.flowFormData.validate(res => {
        if (res) {
          this.$confirm("提交操作后不可更改，是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              if (this.flowState.step === 0 && this.flowState.firstSend) {
                // 第一次发起
                this.addAndStartFlow();
              } else {
                this.handleResolve();
              }
            })
            .catch(() => {
              return;
            });
        } else {
          this.$message.warning("请检查必填项");
        }
      });
    },

    /**
     * @description: 打包业务数据
     * @param {type}
     * @return:
     */
    wrapBusinessData() {
      this.businessData = {
        id: this.flowFormData.id,
        subjectId: this.flowFormData.subjectId,
        tenders: this.flowFormData.tenders,
        major: this.flowFormData.major,
        contractName: this.flowFormData.contractName,
        contractId: this.flowFormData.contractId,
        company: this.flowFormData.company,
        contractAmount: this.flowFormData.contractAmount,
        amountPaid: this.flowFormData.amountPaid,
        timePaid: this.flowFormData.timePaid,
        payAmountChi: this.flowFormData.payAmountChi,
        payAmountNum: this.flowFormData.payAmountNum,
        payBasis: this.flowFormData.payBasis,
        bank: this.flowFormData.bank,
        bankCardName: this.flowFormData.bankCardName,
        bankCardId: this.flowFormData.bankCardId,
        contact: this.flowFormData.contact,
        phone: this.flowFormData.phone,
        applicant: this.flowFormData.applicant,
        createTime: this.flowFormData.createTime //创建时间
      };
    },

    /**
     * @description: 发起流程
     * @param {type}
     * @return:
     */
    addAndStartFlow() {
      // 第一次发起
      this.wrapBusinessData();
      this.businessData.createTime = formatDate(
        new Date(),
        "yyyy-MM-dd hh:mm:ss"
      );
      this.config.loading = true;
      console.log("开始新增了");
      console.log("参数是");
      console.log(this.businessData);

      this.$api.payapply
        .add(this.businessData)
        .then(res => {
          console.log("add payapply res");
          console.log(res);
          if (res.code === 200) {
            this.flowStartParam.businessid = res.data.id;
            this.$api.startitem
              .starttask(this.flowStartParam)
              .then(res => {
                this.config.loading = false;
                if (res.code === 200) {
                  this.$message.success("发送成功：申请已提交勘察总体审批");
                  this.refresh();
                } else {
                  this.$message.error("发送失败：" + res.msg);
                }
              })
              .catch(err => {
                this.config.loading = false;
                this.$message.error("发送失败：" + err);
              });
          } else {
            this.config.loading = false;
            this.$message.error("提交表单失败:" + res.msg);
          }
        })
        .catch(err => {
          this.config.loading = false;
          this.$message.error("提交表单失败:" + err);
        });
    },

    /**
     * @description: 通过或重新发起
     * @param {type}
     * @return:
     */

    handleResolve() {
      console.log("run");

      // 走审批接口
      if (this.flowState.step === 0 && !this.flowState.firstSend) {
        // 重新发起
        console.log("restart flow");

        this.wrapBusinessData();
        this.$api.payapply
          .modify(this.businessData)
          .then(res => {
            if (res.code === 200) {
              this.flowRunParam.approver = this.currApproveInfo.approver;
              this.flowRunParam.message = this.currApproveInfo.message;
              this.flowRunParam.time = formatDate(
                new Date(),
                "yyyy-MM-dd hh:mm:ss"
              );
              this.$api.startitem
                .approve([this.flowRunParam])
                .then(res => {
                  console.log("approve param");
                  console.log(this.flowState);
                  if (res.code === 200) {
                    this.$message.success("操作成功");
                    this.refresh();
                  }
                })
                .catch(err => {
                  console.log(err);
                });
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        console.log("run flow");

        this.flowRunParam.approver = this.currApproveInfo.approver;
        this.flowRunParam.message = this.currApproveInfo.message + "\n【通过】";
        this.flowRunParam.time = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
        this.$api.startitem
          .approve([this.flowRunParam])
          .then(res => {
            console.log("approve param");
            console.log(this.flowState);
            if (res.code === 200) {
              this.$message.success("操作成功");
              console.log("step:" + this.flowState.step);
              if (this.flowState.step === 3) {
                //添加公告
                // this.myAnnounceDlgConfig.isupdate = false;
                // this.myAnnounceDlgConfig.announceInfo.create_by = "";
                // this.myAnnounceDlgConfig.announceInfo.remark = this.flowFormData.id;
                // this.myAnnounceDlgConfig.announceInfo.subject_id =
                //   glbVar.subjectId;
                // this.myAnnounceDlgConfig.announceInfo.notice_content =
                //   "支付申请内容";
                // this.myAnnounceDlgConfig.dialogFormVisible = true;
                let announce = {
                  subject_id: this.flowFormData.subjectId,
                  url: "",
                  remark: this.flowFormData.id,
                  notice_type: "支付申请",
                  role: refRoles,
                  create_by: this.flowFormData.applicant,
                  create_time: this.flowFormData.createTime,
                  notice_content:
                    "【" +
                    this.flowFormData.tenders.split("/")[0] +
                    "】支付申请完成",
                  notice_title:
                    "【" +
                    this.flowFormData.tenders.split("/")[0] +
                    "】支付申请完成",
                  path: this.$route.path
                };

                this.$api.announce
                  .add(announce)
                  .then(res => {
                    this.config.loading = false;
                    if (res.code == 200) {
                      this.$message.success("操作成功!");
                      this.refresh();
                    } else {
                      this.$message.error("操作失败!" + res.msg);
                    }
                  })
                  .catch(err => {
                    this.config.loading = false;
                    this.$message.error("操作失败!" + err);
                  });
              } else {
                this.refresh();
              }
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    /**
     * @description: 驳回
     * @param {type}
     * @return:
     */
    rejectflow() {
      if (this.flowState.step === 0) {
        // 重置
        return;
      }
      this.$refs.flowFormData.validate(res => {
        if (res) {
          this.$confirm("提交操作后不可更改，是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            // 走审批拒绝接口
            this.flowRunParam.approver = this.currApproveInfo.approver;
            this.flowRunParam.message =
              this.currApproveInfo.message + "\n【驳回】";
            this.flowRunParam.time = formatDate(
              new Date(),
              "yyyy-MM-dd hh:mm:ss"
            );
            this.$api.startitem.disapprove(this.flowRunParam).then(res => {
              console.log("disapprove param");
              console.log(this.flowRunParam);
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.refresh();
              }
            });
          });
        } else {
          this.$message.warning("请检查必填项");
        }
      });
    },

    /**
     * @description: 初始化审批意见
     * @param {type}
     * @return:
     */
    initComments(id) {
      this.$api.startitem
        .getcomment({ businessType: 11, businessId: id })
        .then(res => {
          if (res.code === 200) {
            this.flowComments = res.data;
            let firstCheck = this.flowComments.filter(item => {
              return item.group_name === "勘察总体";
            });
            let secondCheck = this.flowComments.filter(item => {
              return item.group_name === "咨询单位";
            });
            let thirdCheck = this.flowComments.filter(item => {
              return item.group_name === "建设单位";
            });

            this.handleCommentShow(firstCheck, secondCheck, thirdCheck);
          } else {
            console.log("get comment data err res.msg:" + res.msg);
          }
        })
        .catch(err => {
          console.log("get comment data err:" + err);
        });
    },

    handleCommentShow(fi, se, th) {
      if (fi.length > 0) {
        this.flowFormData.firstApprover = fi[fi.length - 1].approver;
        this.flowFormData.firstTime = fi[fi.length - 1].time;
        this.flowFormData.firstMessage = fi[fi.length - 1].message;
      }
      if (se.length > 0) {
        this.flowFormData.secondApprover = se[se.length - 1].approver;
        this.flowFormData.secondTime = se[se.length - 1].time;
        this.flowFormData.secondMessage = se[se.length - 1].message;
      }
      if (th.length > 0) {
        this.flowFormData.thirdApprover = th[th.length - 1].approver;
        this.flowFormData.thirdTime = th[th.length - 1].time;
        this.flowFormData.thirdMessage = th[th.length - 1].message;
      }
    },

    /**
     * @description: 改变当前流程节点值
     * @param {type}
     * @return:
     */
    changeStep(step) {
      this.flowConfig.stepConfig.active = step;
      this.flowState.step = step;
      this.formConfig.currentRule = this.formConfig.rules["node_" + (step + 1)];

      if (step === 0) {
        if (!this.flowState.firstSend) {
          this.flowConfig.btns = {
            resolveText: "重新发送",
            rejectText: "重置",
            cancelText: "返回"
          };
        } else {
          this.flowConfig.btns = {
            resolveText: "发送",
            rejectText: "重置",
            cancelText: "返回"
          };
        }
      } else {
        this.flowConfig.btns = {
          resolveText: "通过",
          rejectText: "驳回",
          cancelText: "取消"
        };
      }
    },

    /**
     * @description: 取消流程，返回
     * @param {type}
     * @return:
     */
    cancelflow() {
      this.refresh();
    }
  },

  computed: {
    currApproveInfo() {
      let index = this.flowState.step;
      if (index === 0) {
        return {
          approver: this.flowFormData.applicant,
          message: "重新发起申请"
        };
      }
      if (index === 1) {
        return {
          approver: this.flowFormData.firstApprover,
          message: this.flowFormData.firstMessage
        };
      } else if (index === 2) {
        return {
          approver: this.flowFormData.secondApprover,
          message: this.flowFormData.secondMessage
        };
      } else
        return {
          approver: this.flowFormData.thirdApprover,
          message: this.flowFormData.thirdMessage
        };
    }
  }
};
</script>
<style lang='less' scoped>
.col-flex {
  box-sizing: border-box;
  padding-top: 30px;
  height: 100%;

  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }

  .maincont-container {
    height: 100%;
    margin-top: 3px;
    .tab-container {
      height: 100%;
      /deep/.el-tabs {
        height: 100%;

        .el-tabs__header {
          margin: 0;
        }
        .el-tabs__content {
          height: calc(~"100% - 40px");
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
    .flow-container {
      height: 100%;
      width: 100%;
      box-sizing: border-box;
      padding-top: 60px;

      .flow-step {
        width: 100%;
        height: 60px;
        margin-top: -60px;
      }

      .flow-form {
        text-align: center;
        height: calc(~"100% - 10px");
        // height: 100%;

        table .form-label {
          background-color: #efefef;
        }

        .form-title {
          margin: 10px !important;
        }

        .form-data {
          border-collapse: collapse;
          margin: auto;
          width: 70%;
          font-size: 13px;
        }
        .btns {
          width: 70%;
          margin: 20px auto;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }

  .scrollable {
    overflow: auto;
  }

  /deep/.el-form-item {
    padding: 0px;
    margin: 0px;
    .el-form-item__content {
      line-height: normal;
    }
    .el-select {
      display: block;
    }
  }
  /deep/.addbutton-con {
    button {
      box-shadow: 0px 0px 0px 3px #66b1ff55;
    }
    i {
      font-size: 20px;
    }
    z-index: 100;
    position: absolute;
    top: 10px;
    right: 10px;
    margin: 5px;
    height: 40px;
    border-radius: 50%;
    // box-shadow: 0px 0px 0px 2px gray;
  }
}
</style>